package leetCode;

/**
 * 1658. 将 x 减到 0 的最小操作数
 * https://leetcode.cn/problems/minimum-operations-to-reduce-x-to-zero/description/
 */
class Solution4 {
    public int minOperations(int[] nums, int x) {
        int sum = 0, targert = 0;//总和，中间的目标总和
        int n = nums.length;
        for(int i = 0; i < n; i++) {
            sum += nums[i];
        }
        targert = sum - x;
        if(targert < 0) return -1;
        int windowsSum = 0;//窗口的总和
        int ret = Integer.MAX_VALUE;//最终返回值
        for(int left = 0, right = 0; right < n; right++) {
            windowsSum += nums[right];//进窗口
            while(windowsSum > targert) {
                windowsSum -= nums[left];//出窗口
                left++;
            }
            if(windowsSum == targert) {
                //更新结果
                ret = Math.min(ret, n - (right - left + 1));
            }
        }
        return ret == Integer.MAX_VALUE ? -1 : ret;
    }
}